package org.mobile.makibis;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.mobile.makibis.species.DataGetter;
import org.mobile.makibis.util.ContentLoader;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class SearchSpecies extends Activity {
	
	final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this);
	
	private WebView speciesDesc;
	private Gallery gallery;
	private ListView listView = null;
	
	private String[] tax = {"Domain", "Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Species"};
	private String feedURL, makibisURL;
	private String breadcrumb;
	
	private ListAdapter adapter;
	private ArrayList<JSONObject> itemList;
	private JSONArray jsonArray;
	private TextView[] breadCrumb = new TextView[8];
	private int taxPointer = -1;
	
	ContentLoader cont = new ContentLoader();

	public void intialize(){
		
		breadCrumb[0] = (TextView)findViewById(R.id.bread_domain);
    	breadCrumb[1] = (TextView)findViewById(R.id.bread_kingdom);
    	breadCrumb[2] = (TextView)findViewById(R.id.bread_phylum);
    	breadCrumb[3] = (TextView)findViewById(R.id.bread_class);
    	breadCrumb[4] = (TextView)findViewById(R.id.bread_order);
    	breadCrumb[5] = (TextView)findViewById(R.id.bread_family);
    	breadCrumb[6] = (TextView)findViewById(R.id.bread_genus);
    	breadCrumb[7] = (TextView)findViewById(R.id.bread_species);
    	
    	for(int i=0;i<breadCrumb.length;i++)
    	breadCrumb[i].setOnClickListener(new BreadCrumbListener(i));
    	
		
		listView = (ListView)findViewById(R.id.item_list);
		itemList = new ArrayList<JSONObject>();
        adapter = new ListAdapter(SearchSpecies.this, R.layout.breadcrumbs, itemList);
        listView.setAdapter(adapter);
    	
		gallery = (Gallery)findViewById(R.id.gallery);    
		gallery.setAdapter(new ImageAdapter(this));

		
		speciesDesc = (WebView)findViewById(R.id.speciesDesc);
		speciesDesc.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
		speciesDesc.getSettings().setPluginsEnabled(true);
        speciesDesc.getSettings().setAllowFileAccess(true);
        speciesDesc.getSettings().setJavaScriptEnabled(true);
        speciesDesc.loadUrl("file:///android_asset/species.html");
	}
	
	public void initializeListeners(){
		 
	 listView.setOnItemClickListener(new OnItemClickListener() {
        	@Override
			public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
        		
        		
				try{
					if(tax[taxPointer].equals("Species")){
						feedURL += "/" + jsonArray.getJSONObject(pos).getString("ID");
						
						JSONObject object = new JSONObject(cont.loadJSON(feedURL));
						String speciesName = object.getString("name");
						viewSpecies(speciesName);					
					}
					else{
						feedURL += "/" + jsonArray.getJSONObject(pos).getString("ID") + "/" + tax[++taxPointer].toLowerCase();
						setupContent(cont.loadJSON(feedURL));						
					}
					showBreadCrumb(taxPointer);
				}catch(JSONException e){ e.printStackTrace(); }
			}
		});
	 
		gallery.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView parent, View v, int position, long id) {
				//Toast.makeText(AndroidXActivity.this, "" + position, Toast.LENGTH_SHORT).show();
			}
        });
	}
	 
	public void hideSpeciesDescription(){
		listView.setVisibility(View.VISIBLE);
		gallery.setVisibility(View.GONE);
		speciesDesc.setVisibility(View.GONE);
	 }
	
	public void viewSpecies(String speciesName) throws JSONException{
		DataGetter getter = new DataGetter(makibisURL);
		
		int speciesID = getter.getSpeciesID(speciesName);
		JSONObject object = getter.getSpeciesData(speciesID);
		
		speciesDesc.loadUrl("javascript:loadSpeciesInfo(\"" + object.getString("vernacularName") + "\",\"" + object.getString("reference") + "\",\"" + object.getString("sex") + "\",\"" + object.getString("characteristic") + "\",\"" + object.getString("threatStatus") + "\",\"" + object.getString("distribution") + "\",\"" + object.getString("country") + "\",\"" + object.getString("continent") + "\",\"" + object.getString("longitude") + "\",\"" + object.getString("latitude") +  "\")");
		speciesDesc.loadUrl("javascript:loadSpeciesTaxonomy(\""+ object.getString("domain")+ "\",\"" + object.getString("kingdom")+ "\",\"" + object.getString("phylum")+ "\",\"" + object.getString("class") + "\",\"" + object.getString("order")+ "\",\"" + object.getString("family")+ "\",\"" + object.getString("genus")+ "\",\"" + object.getString("subgenus") + "\",\"" + object.getString("species") + "\",\"" + object.getString("subspecies") +  "\")");
		
		gallery.setVisibility(View.VISIBLE);
		listView.setVisibility(View.GONE);
		speciesDesc.setVisibility(View.VISIBLE);
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);
        intialize();
        initializeListeners();
    }
    
    @Override
	protected void onPostCreate(Bundle icicle) {
		super.onPostCreate(icicle);
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				feedURL = getResources().getString(R.string.feed_url);
				makibisURL = getResources().getString(R.string.feed_url);
				feedURL += "/"+tax[++taxPointer].toLowerCase();
				setupContent(cont.loadJSON(feedURL));
			}
		}).start();
	}
    
    private class BreadCrumbListener implements OnClickListener {
    	private int x;

    	public BreadCrumbListener(int x){
			this.x = x;
    	}
    	
    	@Override
		public void onClick(View v) {
    		Log.d("DEBUG", "breadcrumblistener onclick");
    		hideSpeciesDescription();
    		breadcrumb = feedURL.substring(0, feedURL.indexOf(tax[x].toLowerCase())) + tax[x].toLowerCase();
    		showBreadCrumb(x);
    		setupContent(cont.loadJSON(breadcrumb));
    		feedURL = breadcrumb;
    		taxPointer = x;
		}    	
    }
    
    private void showBreadCrumb(int index){
    	Log.d("DEBUG", "showbreadcrumb");
    	for(int i=0; i<breadCrumb.length; i++){
    		if(i<=index) breadCrumb[i].setVisibility(View.VISIBLE);
    		else breadCrumb[i].setVisibility(View.GONE);
    	}
    }
    
    private void setupContent(final String jsonContent) {
    	Log.d("DEBUG", "setupContent");
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				try {
					adapter.clear();
					JSONObject content = new org.json.JSONObject(jsonContent.toString());
					jsonArray = content.getJSONArray("data");
					if(jsonArray != null){
						for(int i=0; i<jsonArray.length(); i++) {
							JSONObject o = jsonArray.getJSONObject(i);						
							adapter.add(o);
						}
					}
		            //adapter.notifyDataSetChanged();
				
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
 
    private class ListAdapter extends ArrayAdapter<JSONObject>{
    	
    	public ListAdapter(Context context, int resourceID, ArrayList<JSONObject> objects) {
    		super(context, resourceID, objects);Log.d("DEBUG", "ListAdapter");
    	}
    	
    	public View getView(int position, View convertView, ViewGroup parent) {
    		View v = convertView;
    		if (v == null) {
    			LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			v = inflater.inflate(R.layout.breadcrumbs, null);
    		}    		
			JSONObject o =  this.getItem(position);
			if (o != null) {
				TextView tvn = (TextView) v.findViewById(R.id.item_name);
				try{
					if(tvn != null){
						tvn.setText(o.getString("name"));
						Log.d("tvn", o.getString("name"));
					}
				}catch(JSONException e){}  
    		}
            return v;
    	}
    }
    
    public class ImageAdapter extends BaseAdapter {

        int mGalleryItemBackground;
        private Context mContext;
        
        private Integer[] mImageIds = {R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7};

        public ImageAdapter(Context c) {
            mContext = c;
            TypedArray attr = mContext.obtainStyledAttributes(R.styleable.Images);
            mGalleryItemBackground = attr.getResourceId(
                    R.styleable.Images_android_galleryItemBackground, 0);
            attr.recycle();
            Log.d("DEBUG", "ImageAdapter");
        }

        public int getCount() {
            return mImageIds.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }
        
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView = new ImageView(mContext);

            imageView.setImageResource(mImageIds[position]);
            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            imageView.setBackgroundColor(Color.TRANSPARENT); //imageView.setBackgroundResource(mGalleryItemBackground);
            imageView.setLayoutParams(new Gallery.LayoutParams(Gallery.LayoutParams.WRAP_CONTENT, Gallery.LayoutParams.WRAP_CONTENT)); //imageView.setLayoutParams(new Gallery.LayoutParams(250, 200));
            
            return imageView;
        }
    }
    public class MyJavaScriptInterface {
		Context mContext;
		
		MyJavaScriptInterface(Context c) {
			mContext = c;
		}
	}
}